<template>
  <div class="ff-regular">
    <div class="shipping-address">
      <div class="shipping-title">
        <slot name="title">
          <span class="label ff-bold">{{ $t("submitParcel.shippingAddress") }}</span>
        </slot>
        <div class="left">
          <span class="fun-text col-1e1" @click="addMet">+{{ $t('submitParcel.addressAdd') }}</span>
          <span class="fun-text" @click="selectAddressPop = true">{{ $t('submitParcel.addressChange') }}</span>
        </div>
      </div>
      <div class="current-address">
        <!-- <img class="bg-border" src="@/assets/images/parcel/bg-border.png" alt="" /> -->
        <div class="address-msg">
          <span class="icon">
            <img src="@/assets/images/icons/icon_address.png" alt="" />
          </span>

          <div class="msg-address">
            {{ currentAddr.countryText }} {{ currentAddr.provinceText }} {{ currentAddr.cityText }} {{
              currentAddr.areaText }} {{ currentAddr.addressDetail }} {{ currentAddr.doorNumber ?
              `${currentAddr.doorNumber} ` : currentAddr.consigneeCompany ? `${currentAddr.consigneeCompany}` : '' }}
          </div>


          <div class="msg-footer">
            <div class="footer-default ff-bold" v-if="currentAddr.isDefault == true">{{
              $t("submitParcel.defaultAddress") }}
            </div>
            <Divider type="vertical" />
            <div class="msg-name">
              <div>{{ currentAddr.name }} {{ currentAddr.surname }}</div>
              <div class="name-phone">{{ currentAddr.regionCode ? `+${currentAddr.regionCode}` : currentAddr.regionCode
                }}
                {{ phoneHide(currentAddr.mobile) }}</div>
              <div>{{ currentAddr.postalCode }}</div>
            </div>
            <Divider type="vertical" />
            <div class="msg-flex footer-edit" v-if="currentAddr" @click="editAddress(currentAddr)">
              <img src="@/assets/images/parcel/edit-aeb.png" alt="" class="edit-img" />
              <span class="edit-span">{{ $t("submitParcel.edit") }}</span>
            </div>
            <div class="msg-flex">

            </div>
          </div>
        </div>
      </div>
    </div>
    <!--选择地址弹窗-->
    <Modal width="60%" class-name="vertical-center-modal" class="pop-address" v-model="selectAddressPop"
      :title="$t('submitParcel.selectAddress')">
      <div class="user-addr">
        <div class="content">
          <!--地址列表-->
          <div class="table-wrap">
            <div class="table">
              <div class="table-header ff-bold">
                <Row>
                  <Col span="6">
                  <div class="th">{{ $t("submitParcel.addressee") }}</div>
                  </Col>
                  <Col span="14">
                  <div class="th">{{ $t("submitParcel.detailedAddress") }}</div>
                  </Col>
                  <Col span="4">
                  <div class="th">{{ $t("submitParcel.operation") }}</div>
                  </Col>
                </Row>
              </div>
              <div class="table-content">
                <Row v-for="(item, index) in userAddressList" :key="index" class="table-tr tr-active">
                  <Col span="6">
                  <div class="td">{{ item.recipientName.split(",")[0] }} {{ item.recipientName.split(",")[1] }}</div>
                  </Col>
                  <Col span="14">
                  <div class="td">
                    <div>{{ item.postalCode }} +{{ item.regionCode }} {{ item.mobile }}</div>
                    <div>{{ item.addressDetail }} {{ item.areaText ? item.areaText + "," : "" }}{{ item.cityText ?
                      item.cityText + "," : "" }}{{ item.provinceText }},{{ item.countryText }}</div>
                    <div class="tag">
                      {{ item.townText }}
                    </div>
                  </div>
                  </Col>
                  <Col span="4">
                  <div class="td fun">
                    <Button @click="onSelect(item)">{{ $t("submitParcel.selectAddress") }}</Button>
                  </div>
                  </Col>
                </Row>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div slot="footer"></div>
    </Modal>
    <!-- 添加or编辑收货地址 -->
    <create-user-address ref="createRef" @updateMet="getAddressList"></create-user-address>
  </div>
</template>

<script>
import { addressAdd, addressEdit, addressList, deleteAddress } from "@/api/address";
import { countryAddressList, cityApiList } from "@/api/administrativedivisions";
import { mapState } from "vuex";
import { phoneHide } from "@/common/common";
import { pointUser } from "@/common/point/api-hook";//打点日志
import createUserAddress from '../user/components/create-user-address.vue';
export default {
  components: { createUserAddress },
  name: "user-shipping-address",
  props: {
    defaultAddress: Object,
    // 收获地址的类型 parcel提交运单 confirm确认订单
    addressType: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      phoneHide,
      orderEditType: true, // 如果这个状态是true, 那么当执行编辑保存的时候执行新增方法，如果是false说明已经修改过，就执行编辑方法
      selectAddressPop: false,
      currentAddr: "", // 默认地址
      loading: false,
      userAddressList: [],
      showPop: false,
      ruleValidate: {
        name: [
          { required: true, message: this.$t("user.pleaseEnter") + this.$t("user.name"), trigger: "blur" },
          { type: 'string', max: 17, message: this.$t('ruleValidate.name'), trigger: 'change' }
        ],
        surname: [
          { required: true, message: this.$t("user.pleaseEnter") + this.$t("personal.LastName"), trigger: "blur" },
          { type: 'string', max: 17, message: this.$t('ruleValidate.name'), trigger: 'change' }
        ],
        addressDetail: [{ required: true, message: this.$t("ruleValidate.address_tip"), trigger: "blur" }],
        postalCode: [{ required: true, message: this.$t("user.pleaseEnter") + this.$t("user.postcode"), trigger: "blur" }],
        mobile: [{ required: true, message: this.$t("user.pleaseEnter") + this.$t("user.mobile"), trigger: "blur" }],
        countryCode: [{ required: true, message: this.$t("user.InputAddress"), trigger: "change" }],
        provinceCode: [{ required: true, message: this.$t("user.pleaseEnter") + this.$t("user.province"), trigger: "change" }],
        cityCode: [{ required: true, message: this.$t("user.pleaseEnter") + this.$t("user.city"), trigger: "change" }],
      },
      formValidate: {
        id: "",
        surname: "", // 姓
        name: "", // 名
        addressDetail: "", // 街道地址，详细地址
        areaCode: "", // 区code
        areaText: "", // 区文本
        cityCode: "", // 市code
        cityText: "", // 市文本
        countryCode: "", // 国家编码
        districtCode: "", // 地址编码
        regionCode: "", // 手机国际区号
        regionCodeCountry: "", // 区号+国家
        regionCountry: '', // 区号国家
        isDefault: false, // 是否默认地址
        mobile: "", // 手机号
        phone: "", // 电话
        postalCode: "", // 邮政编码
        provinceCode: "",
        provinceText: "", // 省份文本
        recipientName: "", // 收件人姓名
        townText: "", // 文本
      },
      currentCountryImage: "", // 当前国家图片
      cityList: [], // 市区列表
      provinceList: [],
      errorMessage: '',
    };
  },
  computed: {
    ...mapState({
      countryList: (state) => {
        let list = [];
        if (state.config.config) {
          list = state.config.config.countryList;
        }
        return list;
      },
      regionCodeList: (state) => {
        // 国际区号
        let list = [];
        if (state.config.config) {
          list = state.config.config.regionCodeList;
        }
        return list;
      },
    }),
  },
  created() {
    if (this.addressType == 'parcel') {
      this.currentAddr = { ...this.currentAddr, ...this.defaultAddress };
    }
    this.getAddressList();
  },
  methods: {
    addMet() {
      pointUser('actions', '2007');
      this.$refs.createRef.open();
    },
    validateInput() {
      const regex = /^[0-9()\\-]*$/;
      if (!regex.test(this.formValidate.mobile)) {
        this.errorMessage = this.$t('user.input_rules_tip');
      } else {
        this.errorMessage = '';
      }
    },
    onSelect(addInfo) {
      // 选择了地址
      if (this.orderEditType) {
        this.orderEditType = false;
      }
      this.currentAddr = addInfo;
      this.currentAddr.name = addInfo.recipientName.split(",")[0];
      this.currentAddr.surname = addInfo.recipientName.split(",")[1];
      this.selectAddressPop = false;
      this.$emit("on-change", this.currentAddr);
    },
    onSelectCity(info) {
      this.cityList.forEach((item) => {
        if (item.id == info.value) {
          this.formValidate.postalCode = item.postalCode;
        }
      })
      // 选择市
      this.formValidate.cityText = info.label;
      this.formValidate.areaCode = "";
      this.formValidate.areaText = "";
    },
    onSelectProvince(info) {
      // 选择省份
      this.getCityList(info.value, "cityList");
      this.formValidate.provinceText = info.label;
      this.formValidate.cityCode = "";
      this.formValidate.areaCode = "";
      this.formValidate.cityText = "";
      this.formValidate.areaText = "";
    },
    getCityList(code, type) {
      // 获取
      this[type] = [];
      cityApiList(code)
        .then((res) => {
          this[type] = res.result;
          this.gloabalLoading = false;
        })
        .catch(() => {
          this.gloabalLoading = false;
        });
    },
    onCountry(value) {
      this.gloabalLoading = true;
      // 选择国家
      let info = this.countryList.find((item) => {
        return item.code == value;
      });
      this.formValidate.countryText = info.text;
      this.currentCountryImage = info.flagImg;
      this.formValidate.provinceCode = "";
      this.formValidate.cityCode = "";
      this.formValidate.areaCode = "";
      this.formValidate.provinceText = "";
      this.formValidate.cityText = "";
      this.formValidate.areaText = "";
      this.onCountryAddressList(info.code, "provinceList");
    },
    onCountryAddressList(code, type) {
      // 获取
      this[type] = [];
      countryAddressList(code)
        .then((res) => {
          this[type] = res.result;
          this.gloabalLoading = false;
        })
        .catch(() => {
          this.gloabalLoading = false;
        });
    },
    editAddress(info) {
      this.$refs.createRef.open(info);
    },
    // 区号赋值
    regionChange(item) {
      let selectedOption = this.regionCodeList.find((option) => option.code + option.regionCountry === item.value);
      this.formValidate.regionCode = selectedOption.code || "";
      this.formValidate.regionCountry = selectedOption.regionCountry || "";
    },
    onAddressAdd() {
      // 添加地址
      this.$refs.formValidate.validate((valid) => {
        if (valid) {
          if (!this.formValidate.countryCode || !this.formValidate.provinceCode || (!this.formValidate.cityCode && this.cityList.length > 0)) {
            this.$Message.error(this.$t("user.InputAddress"));
            return;
          }
          if (!this.formValidate.surname) {
            this.$Message.error(this.$t("user.pleaseEnter") + this.$t("personal.LastName"));
            return;
          }
          if (!this.formValidate.regionCode) {
            this.$Message.error(this.$t("user.pleaseSelect") + this.$t("user.mobileAreaCode"));
            return;
          }

          this.loading = true;
          this.formValidate.recipientName = `${this.formValidate.name},${this.formValidate.surname}`;
          addressAdd(this.formValidate)
            .then((res) => {
              pointUser('actions', '2008');
              this.$Message.success(this.$t("user.addSuccessfully"));
              this.loading = false;
              this.showPop = false;
              this.getAddressList();
              this.setFormValidate();
            })
            .catch(() => {
              this.loading = false;
            });
        }
      });
    },
    hidePop() {
      // 隐藏弹窗
      this.showPop = false;
      this.setFormValidate();
    },
    setFormValidate() {
      this.currentCountryImage = "";
      this.formValidate = {
        id: "",
        surname: "", // 姓
        name: "", // 名
        addressDetail: "", // 街道地址，详细地址
        areaCode: "", // 区code
        areaText: "", // 区文本
        cityCode: "", // 市code
        cityText: "", // 市文本
        countryCode: "", // 国家编码
        countryText: "",
        districtCode: "", // 地址编码
        regionCode: "", // 手机国际区号
        isDefault: false, // 是否默认地址
        mobile: "", // 手机号
        phone: "", // 电话
        postalCode: "", // 邮政编码
        provinceCode: "",
        provinceText: "", // 省份文本
        recipientName: "", // 收件人姓名
        townText: "", // 文本
        regionCountry: "",
        regionCodeCountry: "", // 区号+国家
      };
    },
    onDeleteAddress(id) {
      // 删除地址
      deleteAddress(id).then((res) => {
        this.$Message.success(this.$t("submitParcel.deletedSuccessfully"));
        this.getAddressList();
      });
    },

    onAddressEdit() {
      console.log("编辑了");

      // 编辑地址
      this.$refs.formValidate.validate((valid) => {
        if (valid) {
          if (!this.formValidate.countryCode || !this.formValidate.provinceCode || (!this.formValidate.cityCode && this.cityList.length > 0)) {
            this.$Message.error(this.$t("user.InputAddress"));
            return;
          }
          if (!this.formValidate.surname) {
            this.$Message.error(this.$t("user.pleaseEnter") + this.$t("user.surname"));
            return;
          }
          if (!this.formValidate.regionCode) {
            this.$Message.error(this.$t("user.pleaseSelect") + this.$t("user.mobileAreaCode"));
            return;
          }
          // if (this.orderEditType) {
          //   this.onAddressAdd(true);
          //   return false;
          // }
          this.loading = true;
          this.formValidate.recipientName = `${this.formValidate.name},${this.formValidate.surname}`;
          addressEdit(this.formValidate)
            .then((res) => {
              this.$Message.success(this.$t("submitParcel.changeSuccessfully"));
              this.loading = false;
              this.showPop = false;
              this.currentAddr = { ...this.currentAddr, ...this.formValidate };
              this.getAddressList();
              this.setFormValidate();
            })
            .catch(() => {
              this.loading = false;
              this.setFormValidate();
            });
        }
      });
    },
    onDelete() {
      this.$Modal.confirm({
        title: this.$t("submitParcel.removeAddress"),
        content: this.$t("submitParcel.confirmDeleteAddress"),
      });
    },
    getAddressList() {
      // 获取地址列表
      addressList().then((res) => {
        if (this.addressType == 'confirm') {
          let arr = res.result.filter((item) => {
            return item.isDefault == true;
          })
          if (arr.length > 0) {
            this.currentAddr = arr[0];
            this.currentAddr.name = arr[0].recipientName.split(',')[0];
            this.currentAddr.surname = arr[0].recipientName.split(',')[1];

            this.$emit('on-change', this.currentAddr);
          } else {
            if (res.result.length > 0) {
              this.currentAddr = res.result[0];
              this.currentAddr.name = res.result[0].recipientName.split(',')[0];
              this.currentAddr.surname = res.result[0].recipientName.split(',')[1];

              this.$emit('on-change', this.currentAddr);
            }
          }
        }
        this.userAddressList = res.result;
      });
    },
  },
};
</script>

<style scoped lang="less">
.shipping-address {
  border-radius: 8px;
  border: 1px solid #F1F1F1;
  background: #FFF;
  padding: 30px;

  .shipping-title {
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 16px;

    .label {
      color: #2F333A;
      font-weight: bold;
    }

    .left {
      display: flex;
      align-items: center;
      margin-right: 32px;

      .fun-text {
        display: block;
        cursor: pointer;
        margin-left: 24px;
        color: @primary-color;
        font-size: 13px;
      }

      .col-1e1 {
        color: #1E1714;
      }
    }
  }

  .current-address {
    position: relative;
    margin-top: 16px;

    .bg-border {
      display: block;
      width: 100%;
    }

    .address-msg {
      padding: 20px;
      border-radius: 8px;
      border: 1px solid #FF186B;
      position: relative;
      padding-left: 60px;

      .icon {
        position: absolute;
        top: 25px;
        left: 20px;
        width: 20px;
        height: 20px;
        border-radius: 50%;
        overflow: hidden;

        img {
          width: 100%;
          height: 100%;
        }
      }

      .msg-name {
        display: flex;
        align-items: center;
        font-size: 13px;
        height: 18px;
        color: #333;

        .name-phone {
          margin: 0 10px 0 10px;
        }
      }

      .msg-address {
        color: #2F333A;
        font-size: 12px;
        line-height: 32px;
        font-weight: 600;
        min-height: 32px;
      }

      .msg-footer {
        // position: absolute;
        width: 100%;
        display: flex;
        align-items: center;
        box-sizing: border-box;
        margin-top: 10px;
        // padding: 5px;

        .msg-flex {
          display: flex;
          align-items: center;
        }

        .footer-default {
          height: 18px;
          border-radius: 8px;
          padding: 0px 6px;
          box-sizing: border-box;
          color: #FF186B;
          font-size: 12px;
          font-weight: bold;
          display: flex;
          align-items: center;
          justify-content: center;

          border-radius: 4px;
          background: #FFEDF3;
        }

        .footer-edit {
          cursor: pointer;
          margin-left: 10px;

          .edit-img {
            width: 14px;
            height: 14px;
          }

          .edit-span {
            font-size: 13px;
            line-height: 18px;
            color: #2F333A;
            margin-left: 6px;
          }
        }
      }
    }






    .address-info {
      position: absolute;
      left: 0;
      top: 0;
      right: 0;
      bottom: 0;
      padding: 30px 40px;
      display: flex;
      justify-content: space-between;

      .left {
        display: flex;
        flex-flow: column;
        // justify-content: space-between;
        height: 100%;

        .receiver {
          color: @t-title-color;

          .name {
            font-size: 24px;
            font-weight: 700;
          }

          .contact {
            margin-left: 24px;
            font-size: 14px;
            font-weight: 500;
          }
        }

        .addr {
          color: @t-text-color;

          span {
            display: block;
            margin-top: 6px;
          }
        }
      }

      .right {
        display: flex;
        flex-flow: column;
        justify-content: space-between;
        height: 100%;

        .select-addr {
          display: flex;
          align-items: center;
          font-size: 12px;
          font-weight: 400;

          .default-addr {
            padding: 2px 12px;
            color: @primary-color;
            background: #fff6f0;
            border-radius: 2px;
          }

          .addr-value {
            padding: 2px 12px;
            margin-left: 8px;
            color: @success-color;
            background: #e6f3ec;
            border-radius: 2px;
          }
        }

        .edit-wrap {
          display: flex;
          align-items: center;
          justify-content: flex-end;

          .edit {
            display: flex;
            align-items: center;
            cursor: pointer;

            img {
              display: block;
              width: 16px;
              flex: 0 0 16px;
              height: 16px;
            }

            span {
              margin-left: 4px;
              color: @primary-color;
              font-size: 14px;
              font-weight: 500;
            }
          }
        }
      }
    }
  }
}

.user-addr {
  height: 300px;
  overflow-y: auto;

  .top {
    .num {
      margin-left: 6px;
      color: @t-text-color;
    }
  }

  .content {
    padding-bottom: 24px;

    .table-wrap {
      .table {
        &-header {
          padding: 12px;
          background: @t-table-header-bg;

          .th {
            color: @t-title-color;
            font-size: 14px;
            font-weight: 600;

            .all {
              cursor: pointer;
            }
          }
        }

        &-content {
          border-top: 1px solid @t-table-border-color;

          .table-tr {
            padding: 12px;
            border-bottom: 1px solid @t-table-border-color;
            color: @t-text-color;
            font-size: 14px;

            .fun {
              span {
                margin-right: 24px;
                color: @t-title-color;
                cursor: pointer;
              }

              .tag {
                border-radius: 4px;
                background: @primary-color;
                color: #ffffff;
                padding: 2px 4px;
              }
            }
          }
        }
      }
    }

    .page {
      text-align: right;
      margin-top: 24px;
    }
  }
}

.pop-address {
  .pop-address-content {
    .region-code {
      display: flex;
      align-items: center;

      .region-code-icon {
        width: 20px;
        height: 20px;
        border-radius: 50%;
        overflow: hidden;
        margin-right: 2px;
      }
    }

    .flex-content {
      .input {}

      .select {
        .option-content {
          display: flex;
          align-items: center;

          .logo {
            display: inline-block;
            width: 30px;
            margin-right: 4px;
          }
        }

        :deep(.ivu-select-input) {
          width: auto !important;
        }
      }

      .country-wrap {
        background-color: #fff;
        border-radius: 4px;
        border: 1px solid #dcdee2;
        padding: 0 8px;
      }
    }
  }
}
</style>
